package com.k12.admim.controller.login;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.protobuf.ServiceException;
import com.k12.admim.model.dto.UserDTO;
import com.k12.admim.rpc.UserFeignClient;
import com.k12.common.model.resp.R;
import com.k12.admim.model.vo.*;
import com.k12.common.util.sign.RsaUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
public class AdminUserController {


    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 登录
     */
    @PostMapping("login")
    public R login(@RequestBody LoginBodyVo loginBodyVo) throws ServiceException {
        String password = null;
        try {
            password = RsaUtils.decryptByPrivateKey(loginBodyVo.getPassword());
        } catch (Exception e) {
            throw new ServiceException("无效密码");
        }
        UserDTO userDTO =userFeignClient.userLogin(loginBodyVo.getUsername(), password);
        if(null == userDTO){
            return R.businessFail("用户名或密码错误");
        }
        StpUtil.login(JSON.toJSONString(userDTO));
        String tokenValue = StpUtil.getTokenInfo().getTokenValue();
        LoginInfoVo loginInfoVo = new LoginInfoVo();
        loginInfoVo.setToken(tokenValue);
        return R.success(loginInfoVo);
    }






}
